#include "IRReceive.h"
#include "NEC.h" // 假设你有 NEC_Decode 函数
#include "SEGGER_RTT.h"

#define GAP_THRESHOLD_US 8000
#define MARK_MIN_US 400
#define MARK_MAX_US 700

IRReceiver_RingHandleTypeDef irReceiver;

// static void IR_ForwardFrame(IRReceiver_RingHandleTypeDef *h)
// {
//     h->frameReady = true;
// }

bool IRReceiver_Begin(IRReceiver_RingHandleTypeDef *h, TIM_HandleTypeDef *htim)
{
    if (!h || !htim)
        return false;

    h->htim = htim;
    h->frameReady = false;
    h->lastCapture = 0;
    h->callback = NULL;
    RingBuff_Init(&h->rawQueue, RingBuff_OVERWRITE_OLD);

    HAL_TIM_Base_Start(htim);
    if (HAL_TIM_IC_Start_IT(htim, TIM_CHANNEL_4) != HAL_OK)
        return false;

    return true;
}

void IRReceiver_Stop(IRReceiver_RingHandleTypeDef *h)
{
    if (!h || !h->htim)
        return;
    HAL_TIM_IC_Stop_IT(h->htim, TIM_CHANNEL_4);
    HAL_TIM_Base_Stop(h->htim);
}

// 中断调用，仅推入队列
void IRReceiver_OnCapture(IRReceiver_RingHandleTypeDef *h, TIM_HandleTypeDef *htim)
{
    if (!h || !htim || h->htim != htim)
        return;

    uint32_t capture = __HAL_TIM_GET_COMPARE(htim, TIM_CHANNEL_4);
    uint32_t delta;
    if (capture >= h->lastCapture)
        delta = capture - h->lastCapture;
    else
        delta = (htim->Instance->ARR - h->lastCapture) + capture + 1;

    h->lastCapture = capture;
    uint32_t delta_us = delta; // 假设 1 tick = 1 us

    RingBuff_PushBack(&h->rawQueue, delta_us);

    // 边沿翻转
    bool falling = (htim->Instance->CCER & TIM_CCER_CC4P) != 0;
    // SEGGER_RTT_printf(0, "count:%d, data:%d, level:%s\r\n",
    //                   h->rawQueue.count - 1,
    //                   delta_us,
    //                   falling ? "mark" : "space");

    if (falling)
        htim->Instance->CCER &= ~TIM_CCER_CC4P;
    else
        htim->Instance->CCER |= TIM_CCER_CC4P;
}

// 轮询解码，检测前导帧
void IRReceiver_PollDecode(IRReceiver_RingHandleTypeDef *h, IrFrame_Def *frame)
{
    if (!h)
        return;

    uint32_t data1, data2;
    while (RingBuff_Count(&h->rawQueue) >= 2 + 2 * NEC_FRAME_BITS)
    {
        // 检测前导头：第一个数据是 mark(9ms)
        RingBuff_PopFront(&h->rawQueue, &data1);
        if (IS_BETWEEN(data1, 8000, 10000))
        {
            // 第二个数据是 space(4.5ms)
            RingBuff_PopFront(&h->rawQueue, &data2);
            if (IS_BETWEEN(data2, 4000, 5000))
            {
                RingBuff_PushFront(&h->rawQueue, data2);
                RingBuff_PushFront(&h->rawQueue, data1);
                h->frameReady = true;
                break;
            }
        }
    }
    // 引导头不对则退出
    if (!h->frameReady)
        return;

    // 判断数据够不够
    uint8_t len = RingBuff_Count(&h->rawQueue);

    // 引导头正确则先保存原始数据
    for (uint8_t i = 0; i < len; i++)
    {
        uint32_t temp;
        RingBuff_PopFront(&h->rawQueue, &temp);
        frame->waveData_un.u16[i] = (uint16_t)(temp & 0xFFFF);
    }
    frame->waveLineNums = len;
    // TODO 可能会有连续波

    // 解码成功
    if (NEC_Decode(frame))
    {
        if (h->callback)
            h->callback(frame);
    }

    h->frameReady = false;
}
